package com.github.baichuan.web.servlet;

import com.github.baichuan.web.security.Authorization;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.http.HttpStatus;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import java.lang.reflect.Method;
import java.util.Arrays;

/**
 * 授权查验拦截器
 * 配合@Authorization注释使用，检查http header:x-authorization-code是否包含@Authorization要求的权限代码
 */
@Slf4j
public class AuthorizationInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
        if(handler instanceof HandlerMethod){
            HandlerMethod handlerMethod = (HandlerMethod) handler;

            Method method = handlerMethod.getMethod();
            Authorization authorization = method.getAnnotation(Authorization.class);
            if(authorization == null)
                return true;

            String codes = request.getHeader("x-authorization-code");
            if(StringUtils.isBlank(codes))
                return false;

            if(Arrays.stream(codes.split(",")).noneMatch(code -> code.equals(authorization.value()))){
                response.setStatus(HttpStatus.FORBIDDEN.value());
                return false;
            }
        }

        return true;
    }
}
